package com.cl.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.common.api.CommonResult;
import com.cl.common.constant.MessageConstant;
import com.cl.common.model.Admin;
import com.cl.common.vo.LoginVo;
import com.cl.mapper.AdminMapper;
import com.cl.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 用户服务实现类
 * </p>
 *
 * @author cl
 * @since 2022-03-13
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 用户登录功能实现
     *
     * @param loginVo:
     * @return CommonResult
     */
    @Override
    public CommonResult login(LoginVo loginVo) {
        String captcha = (String) redisTemplate.opsForValue().get("code");
        if (StringUtils.isEmpty(loginVo.getCode()) || !loginVo.getCode().equalsIgnoreCase(captcha)) {
            return CommonResult.fail(MessageConstant.CODE_FAIL);
        }
        Admin admin = this.baseMapper.selectOne(new LambdaQueryWrapper<Admin>()
                .eq(Admin::getUsername, loginVo.getUsername())
                .eq(Admin::getPassword, SaSecureUtil.md5(loginVo.getPassword())));
        if (admin == null) {
            return CommonResult.fail(MessageConstant.USER_LOGIN_FAIL);
        }
        if (StpUtil.isDisable(admin.getUsername())) {
            return CommonResult.fail(MessageConstant.USER_FAIL);
        }
        StpUtil.login(admin.getUsername(), MessageConstant.DEVICE);
        return CommonResult.success(MessageConstant.LOGIN_SUCCESS, admin);
    }
}
